package org.liukai.servlet_ems.dao;

import org.liukai.servlet_ems.entity.po.User;
import org.liukai.servlet_ems.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @project servlet_ems
 * @create UserDao.java 
 * 
 * @author liukai
 * @date 2016/1/18 15:42
 * @detail 
 */
public class UserDao {

    public static User queryUserByName(String username) {
        Connection conn = DBUtil.getConnection();
        List<User> list = new ArrayList<User>();
        User user = null;
        try {
            //创建PreparedStatement
            PreparedStatement ps = conn.prepareStatement("select * from liukai_user where username = ?");
            //设置参数  第一个参数为上面sql里"？"的下标 第二个为替换值   注意：这里的下标以1开头
            ps.setString(1, username);
            //执行sql
            ResultSet rs = ps.executeQuery();
            while(rs.next()) {
                list.add(rowToUser(rs));
            }
            if(list.size() > 0) {
                return list.get(0);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeConnection(conn);
        }
        return user;
    }


    //将数据库每一行映射为Emp对象
    private static User rowToUser(ResultSet rs) throws SQLException {
        User user = new User();
        user.setUserId(rs.getInt("UserId"));
        user.setUsername(rs.getString("username"));
        user.setName(rs.getString("name"));
        user.setGender(rs.getString("gender"));
        user.setPwd(rs.getString("pwd"));
        return user;
    }
}
